import {
  ParsedTransactionWithMeta,
  ParsedInstruction,
  PartiallyDecodedInstruction,
  PublicKey,
} from '@solana/web3.js';
import {
  View,
  Text,
  GestureResponderEvent,
  TouchableOpacity,
  Linking,
} from 'react-native';
import tw from 'twrnc';

import {primaryColor2, primaryColor3} from '../../../../theme/default';
import {useCallback, useEffect, useState} from 'react';
import {
  formatNumber,
  formatTimestamp,
  parseSolanaScanTxUrl,
  parseValue,
  toShortAddress,
} from '../../../../utils';
import {UserToken} from '../../../../db/models/userTokenModel';
import {useAccountProvider} from '../../../../hooks/useAccountProvider';
import {useTranslation} from 'react-i18next';
import {useSolanaClientProvider} from '../../../../hooks/useSolana/useSolanaClientProvider';

type TokenTxFeeHistoryItemProp = {
  tokenInfo: UserToken;
  txHistory?: ParsedTransactionWithMeta;
  onPress?: (event: GestureResponderEvent) => void;
};

export default function TokenTxFeeHistoryItem({
  tokenInfo,
  txHistory,
  onPress,
}: Readonly<TokenTxFeeHistoryItemProp>) {
  const {solanaClient} = useSolanaClientProvider();
  const [signature, setSignature] = useState<string>();
  const [fee, setFee] = useState<string>();
  const {t} = useTranslation();
  const {userInfo} = useAccountProvider();
  const parseFeeData = async () => {
    const _fee = (txHistory as ParsedTransactionWithMeta).meta?.fee;
    const _signature = (txHistory as ParsedTransactionWithMeta).transaction
      .signatures[0];
    setFee(formatNumber(parseValue(_fee ?? 0, 9), 2, 6));
    setSignature(_signature);
  };

  const handleOpenSolanaScan = useCallback(async () => {
    if (signature !== undefined) {
      const url = parseSolanaScanTxUrl(signature);

      const supported = await Linking.canOpenURL(url);
      if (supported) {
        await Linking.openURL(url);
      }
    }
  }, [signature]);

  useEffect(() => {
    parseFeeData();
  }, [tokenInfo, txHistory, userInfo, solanaClient]);

  return (
    <TouchableOpacity
      onPress={handleOpenSolanaScan}
      style={{paddingVertical: 0}}>
      <View
        style={{
          ...tw.style('flex flex-row items-center justify-between'),
          height: 56,
        }}>
        <View
          style={{
            ...tw.style('flex flex-col gap-1'),
            height: '100%',
            justifyContent: 'center',
          }}>
          <Text style={tw.style(`text-[${primaryColor2}] text-[12px]`)}>
            {t('fees')}
          </Text>
          <Text style={tw.style(`text-[${primaryColor3}] text-[12px]`)}>
            {signature ? toShortAddress(signature) : ''}
          </Text>
        </View>

        <View
          style={{
            ...tw.style('flex flex-col gap-1'),
            height: '100%',
            justifyContent: 'center',
          }}>
          <Text
            style={tw.style(`text-[${primaryColor2}] text-[14px] text-right`)}>
            {fee ? `-${fee}` : '--'}
          </Text>
          <Text
            style={tw.style(`text-[${primaryColor3}] text-[12px] text-right`)}>
            {formatTimestamp(Number(txHistory?.blockTime) * 1000)}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
}
